// 产品列表页面专用JavaScript

// 品牌配置管理
class BrandConfig {
  constructor() {
    this.brands = {};
    this.loaded = false;
  }

  async loadConfig() {
    if (this.loaded) return this.brands;

    try {
      const response = await fetch("/static/config.json");
      const config = await response.json();
      this.brands = config.brands || {};
      this.loaded = true;
      return this.brands;
    } catch (error) {
      console.error("Error loading brand config:", error);
      return {};
    }
  }

  getBrand(brandName) {
    // 产品名转为小写
    brandName = brandName.toLowerCase();
    return this.brands[brandName] || null;
  }

  getBrandLogo(brandName) {
    const brand = this.getBrand(brandName);
    return brand ? brand.logo : null;
  }

  getAllBrands() {
    return this.brands;
  }

  renderBrandFilters(containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    // 保留"全部品牌"按钮，添加其他品牌
    const allBrandsButton = container.querySelector('[data-brand=""]');

    // 清除除了"全部品牌"之外的其他按钮
    const existingButtons = container.querySelectorAll(
      '[data-brand]:not([data-brand=""])'
    );
    existingButtons.forEach((btn) => btn.remove());

    // 添加每个品牌的按钮
    Object.keys(this.brands).forEach((brandKey) => {
      const brand = this.brands[brandKey];
      const button = document.createElement("button");
      button.className = "btn btn-outline brand-filter";
      button.setAttribute("data-brand", brandKey);
      button.textContent = brand.name;

      // 添加点击事件
      button.addEventListener("click", (e) => {
        e.preventDefault();
        const brandValue = e.target.dataset.brand || "";

        // 更新激活状态
        const brandFilters = document.querySelectorAll(".brand-filter");
        brandFilters.forEach((f) => f.classList.remove("active"));
        e.target.classList.add("active");

        // 过滤产品
        productManager.filterByBrand(brandValue);
      });

      container.appendChild(button);
    });
  }
}

// 产品列表管理
class ProductManager {
  constructor() {
    this.products = [];
    this.currentBrand = "";
    this.currentPage = 1;
    this.pageSize = 12;
    this.total = 0;
  }

  async fetchProducts(brand = "", page = 1) {
    try {
      let url = `/api/product?currentPage=${page}&pageSize=${this.pageSize}`;
      if (brand) {
        url += `&brand=${encodeURIComponent(brand)}`;
      }

      const token = this.getAuthToken();

      const headers = {
        "Content-Type": "application/json",
      };

      if (token) {
        headers["Authorization"] = `Bearer ${token}`;
      }

      const response = await fetch(url, { headers });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();

      if (result.code === 1) {
        this.products = result.data.items || [];
        this.total = result.data.total || 0;
        this.currentPage = result.data.currentPage || 1;
        this.pageSize = result.data.pageSize || 10;
        return this.products;
      } else {
        throw new Error(result.message || "API returned error");
      }
    } catch (error) {
      console.error("Error fetching products:", error);
      return [];
    }
  }

  getAuthToken() {
    const cookies = document.cookie.split(";");
    for (let cookie of cookies) {
      const [name, value] = cookie.trim().split("=");
      if (name === "authorized-token") {
        try {
          const tokenData = JSON.parse(decodeURIComponent(value));
          return tokenData.access_token;
        } catch (e) {
          console.error("Error parsing auth token:", e);
          return null;
        }
      }
    }
    return null;
  }

  renderProducts(products, containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    container.innerHTML = "";

    if (products.length === 0) {
      container.innerHTML = '<p class="no-products">暂无产品信息</p>';
      return;
    }

    products.forEach((product) => {
      const productCard = this.createProductCard(product);
      container.appendChild(productCard);
    });
  }

  createProductCard(product) {
    const card = document.createElement("div");
    card.className = "product-card";

    // 根据实际API数据结构处理显示
    const hasPrice = product.price !== undefined;
    const priceDisplay = hasPrice && product?.price?.price > 0
      ? `¥${product?.price?.price}/年`
      : `¥${product?.price?.alternative_standard_price || product?.price?.alternative_wildcard_price || 0}/年`;

    // 验证类型映射
    const validationTypeMap = {
      dv: "DV 域名验证",
      ov: "OV 组织验证",
      ev: "EV 扩展验证",
    };

    // 域名类型映射
    const getDomainTypes = (product) => {
      const types = product?.common_name_types || [];
      if (
        product?.alternative_name_types &&
        product?.alternative_name_types.length > 0
      ) {
        return "多域名证书";
      } else if (types.includes("wildcard")) {
        return "通配符证书";
      } else if (types.includes("standard")) {
        return "单域名证书";
      } else if (types.includes("ipv4")) {
        return "IP证书";
      }
      return "单域名证书";
    };

    // 获取品牌logo
    const brandLogo = brandConfig.getBrandLogo(product.brand);
    const logoHTML = brandLogo
      ? `<img src="${brandLogo}" alt="${product.brand}" style="height: 60px;">`
      : `<svg width="120" height="60" viewBox="0 0 120 60" xmlns="http://www.w3.org/2000/svg">
                <rect width="120" height="60" rx="6" fill="#ffffff" opacity="0.2"/>
                <text x="60" y="36" text-anchor="middle" fill="white" font-size="12">${
                  product.brand || "SSL"
                }</text>
            </svg>`;

    card.innerHTML = `
            <div class="product-header">
                <div class="product-brand">
                    ${logoHTML}
                </div>
                <h3>${
                  validationTypeMap[product.validation_type] || "SSL证书"
                } - ${getDomainTypes(product)}</h3>
                <div class="product-price">${priceDisplay}</div>
            </div>
            <div class="product-body">
                <ul class="product-features">
                    <li><span>验证类型</span><span>${
                      validationTypeMap[product.validation_type] || "DV"
                    }</span></li>
                    <li><span>域名类型</span><span>${getDomainTypes(
                      product
                    )}</span></li>
                    <li><span>签发CA</span><span>${
                      product.ca.charAt(0).toUpperCase() + product.ca.slice(1)
                    }</span></li>
                    <li><span>退款期限</span><span>${
                      product.refund_period || 7
                    }天</span></li>
                </ul>
                <a href="/product?id=${
                  product.id
                }" class="btn btn-primary" style="width: 100%;">查看详情</a>
            </div>
        `;

    return card;
  }

  filterByBrand(brand) {
    this.currentBrand = brand;
    this.currentPage = 1; // 重置到第一页
    this.fetchProducts(brand, 1).then((products) => {
      this.renderProducts(products, "products-container");
      this.renderPagination("pagination-container");
    });
  }

  goToPage(page) {
    this.currentPage = page;

    // 更新URL参数
    const url = new URL(window.location);
    url.searchParams.set("page", page);
    window.history.pushState({}, "", url);

    this.fetchProducts(this.currentBrand, page).then((products) => {
      this.renderProducts(products, "products-container");
      this.renderPagination("pagination-container");
    });
  }

  renderPagination(containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    const totalPages = Math.ceil(this.total / this.pageSize);
    if (totalPages <= 1) {
      container.innerHTML = "";
      return;
    }

    let paginationHTML = '<div class="pagination">';

    // 上一页
    if (this.currentPage > 1) {
      paginationHTML += `<button class="pagination-btn" onclick="productManager.goToPage(${
        this.currentPage - 1
      })">« 上一页</button>`;
    }

    // 页码
    const startPage = Math.max(1, this.currentPage - 2);
    const endPage = Math.min(totalPages, this.currentPage + 2);

    if (startPage > 1) {
      paginationHTML += `<button class="pagination-btn" onclick="productManager.goToPage(1)">1</button>`;
      if (startPage > 2) {
        paginationHTML += `<span class="pagination-ellipsis">...</span>`;
      }
    }

    for (let i = startPage; i <= endPage; i++) {
      const activeClass = i === this.currentPage ? "active" : "";
      paginationHTML += `<button class="pagination-btn ${activeClass}" onclick="productManager.goToPage(${i})">${i}</button>`;
    }

    if (endPage < totalPages) {
      if (endPage < totalPages - 1) {
        paginationHTML += `<span class="pagination-ellipsis">...</span>`;
      }
      paginationHTML += `<button class="pagination-btn" onclick="productManager.goToPage(${totalPages})">${totalPages}</button>`;
    }

    // 下一页
    if (this.currentPage < totalPages) {
      paginationHTML += `<button class="pagination-btn" onclick="productManager.goToPage(${
        this.currentPage + 1
      })">下一页 »</button>`;
    }

    paginationHTML += "</div>";

    // 添加总数信息
    paginationHTML += `<div class="pagination-info">共 ${this.total} 个产品，第 ${this.currentPage} 页，共 ${totalPages} 页</div>`;

    container.innerHTML = paginationHTML;
  }
}

// 全局实例
const brandConfig = new BrandConfig();
const productManager = new ProductManager();

// 页面初始化
function initProductsPage() {
  // 从URL获取当前页参数
  const urlParams = new URLSearchParams(window.location.search);
  const currentPage = parseInt(urlParams.get("page")) || 1;
  productManager.currentPage = currentPage;

  // 加载品牌配置并渲染品牌过滤器
  brandConfig.loadConfig().then(() => {
    // 渲染品牌过滤按钮
    brandConfig.renderBrandFilters("filter-tabs");
  });

  // 初始化"全部品牌"按钮的点击事件
  const allBrandsButton = document.querySelector('[data-brand=""]');
  if (allBrandsButton) {
    allBrandsButton.addEventListener("click", (e) => {
      e.preventDefault();

      // 更新激活状态
      const brandFilters = document.querySelectorAll(".brand-filter");
      brandFilters.forEach((f) => f.classList.remove("active"));
      e.target.classList.add("active");

      // 过滤产品
      productManager.filterByBrand("");
    });
  }

  // 初始加载所有产品
  productManager.fetchProducts("", currentPage).then((products) => {
    productManager.renderProducts(products, "products-container");
    productManager.renderPagination("pagination-container");
  });
}

// 公开函数
window.initProductsPage = initProductsPage;
window.productManager = productManager;
